/*
 * Copyright (c) 2023 zhangfei
 */
.global strlen
.type strlen,@function

strlen:
#ifdef __riscv_vector
    mv 		a3, a0             # Save start
loop:
    vsetvli 	a1, x0, e8, m8, ta, ma  # Vector of bytes of maximum length
    vle8.v 	v8, (a3)      # Load bytes
    csrr    	a1, vl           # Get bytes read
    vmseq.vi 	v0, v8, 0    # Set v0[i] where v8[i] = 0
    vfirst.m 	a2, v0       # Find first set bit
    add     	a3, a3, a1        # Bump pointer
    bltz    	a2, loop         # Not found?

    add	    	a0, a0, a1        # Sum start + bump
    add     	a3, a3, a2        # Add index
    sub     	a0, a3, a0        # Subtract start address+bump

    ret
#else
    and     a5,a0,7
    beqz    a5,5f
    mv      a5,a0
1:
    j       3f
2:
    add     a5,a5,1
    and     a4,a5,7
    beqz    a4,6f 
3:
    lbu     a4,0(a5)
    bnez    a4,2b 
4:
    sub     a0,a5,a0
    ret

5:
    mv      a5,a0
6:
    ld      a3,0(a5)
    ld      a1,.LC0
    ld      a2,.LC1
    j       8f
7:
    ld      a3,8(a5)
    add     a5,a5,8
8:
    add     a4,a3,a1
    not     a3,a3
    and     a4,a4,a3
    and     a4,a4,a2
    beqz    a4,7b 
    lbu     a4,0(a5)
    beqz    a4,4b
9:
    lbu     a4,1(a5)
    add     a5,a5,1
    beqz    a4,4b 
    lbu     a4,1(a5)
    add     a5,a5,1
    bnez    a4,9b
    j       4b
.section .rodata
.align  3
.LC0:
    .dword  -72340172838076673
    .align  3
.LC1:
    .dword  -9187201950435737472
#endif
